<template>
  <!-- 表单 -->
  <el-form inline="true" class="role-form" style="margin-bottom: 20px">
    <el-form-item style="margin-right: 20px">
      <el-input v-model="params.roleName" placeholder="请您输入要搜索的角色名" style="width: 240px" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSearch">搜索</el-button>
      <el-button @click="onReset">重置</el-button>
      <el-button type="primary" :icon="Plus" @click="showAddDialog">新增角色</el-button>
    </el-form-item>
  </el-form>
  <!-- 表格 -->
  <el-table :data="roleList" class="role-table" style="width: 100%">
    <el-table-column prop="roleName" label="角色名" width="180" />
    <el-table-column prop="permissionNames" label="权限" min-width="300">
      <template #default="{ row }">
        <el-tooltip :content="row.permissionNames" placement="top">
          <span class="permission-text" @click="showPermissionDialog(row)">
            {{ row.permissionNames.length > 15 ? row.permissionNames.substring(0, 15) + '...' : row.permissionNames }}
          </span>
        </el-tooltip>
      </template>
    </el-table-column>
    <el-table-column prop="nickName" width="180px" label="创建人" />
    <el-table-column prop="createTime" label="创建时间" width="180px">
      <template #default="{ row }">
        {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
    </el-table-column>
    <el-table-column label="操作" width="100px" fixed="right">
      <template #default="{ row }">
        <el-button type="text" class="red" @click="handleDelete(row)">删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog v-model="permissionDialogVisible" title="权限管理" width="60%">
    <el-form inline="true" style="margin-bottom: 20px">
      <el-form-item style="margin-right: 20px">
        <el-input v-model="permissionInputValue" placeholder="请输入权限名称" style="width: 240px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onPermissionSearch">搜索</el-button>
        <el-button @click="onPermissionReset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-tabs @tab-click="handleTabClick">
      <el-tab-pane label="已关联权限">
        <el-table :data="permissionList" border>
          <el-table-column prop="permissionName" label="权限名" width="180" />
          <el-table-column prop="requestMethod" label="请求方法" width="100" />
          <el-table-column prop="routerPath" label="路由路径" />
          <el-table-column prop="type" label="类型" width="100" />
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button type="text" class="red" @click="handleRemovePermission(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="permissionTotal"
          v-model:current-page="params.pageNum" v-model:page-size="params.pageSize" :page-sizes="[5, 10, 15, 20]"
          :page-size="permissionParams.pageSize" :current-page="permissionParams.pageNum"
          @size-change="handlePermissionSizeChange" @current-change="handlePermissionPageChange" />
      </el-tab-pane>
      <el-tab-pane label="可关联权限">
        <el-table :data="availablePermissionList" border>
          <el-table-column prop="permissionName" label="权限名" width="180" />
          <el-table-column prop="requestMethod" label="请求方法" width="100" />
          <el-table-column prop="routerPath" label="路由路径" />
          <el-table-column prop="type" label="类型" width="100" />
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button type="text" @click="handleAddPermission(row)">添加</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="availablePermissionTotal"
          v-model:current-page="availablePermissionParams.pageNum"
          v-model:page-size="availablePermissionParams.pageSize" :page-sizes="[5, 10, 15, 20]"
          @size-change="handleAvailablePermissionSizeChange" @current-change="handleAvailablePermissionPageChange" />
      </el-tab-pane>
    </el-tabs>
  </el-dialog>

  <el-pagination background size="small" layout="total,sizes,prev,pager,next,jumper" :total="total"
    v-model:current-page="params.pageNum" v-model:page-size="params.pageSize" :page-sizes="[5, 10, 15, 20]"
    @size-change="handleSizeChange" @current-change="handleCurrentChange" />

  <el-dialog v-model="addDialogVisible" title="新增角色" width="30%">
    <el-form :model="addForm" label-width="80px">
      <el-form-item label="角色名">
        <el-input v-model="addForm.roleName" placeholder="请输入角色名" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="addDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleAdd">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from "vue"
import { Plus } from "@element-plus/icons-vue"
import { getRoleListService, deleteRoleService, getRolePermissionListService, addRoleService, removeRolePermissionService, getAvailablePermissionListService, addRolePermissionService } from "@/apis/role";
import { reactive } from "vue";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";

const activeTab = ref('已关联权限'); // 跟踪当前激活的页签

const permissionInputValue = computed({
  get() {
    return activeTab.value === '已关联权限'
      ? permissionParams.permissionName
      : availablePermissionParams.permissionName;
  },
  set(value) {
    if (activeTab.value === '已关联权限') {
      permissionParams.permissionName = value;
    } else {
      availablePermissionParams.permissionName = value;
    }
  }
});

const params = reactive({
  pageNum: 1,
  pageSize: 10,
  roleName: ''
})

const roleList = ref([])
const total = ref(0)
const permissionDialogVisible = ref(false)
const permissionList = ref([])
const permissionTotal = ref(0)
const permissionParams = reactive({
  pageNum: 1,
  pageSize: 10,
  roleId: '',
  permissionId: '',
  permissionName: ''
})

const availablePermissionList = ref([])
const availablePermissionTotal = ref(0)

const availablePermissionParams = reactive({
  pageNum: 1,
  pageSize: 10,
  roleId: '',
  permissionName: '',
  permissionId: ''
})

const addDialogVisible = ref(false)
const addForm = reactive({
  roleName: ''
})

async function getRoleList() {
  const result = await getRoleListService(params);
  roleList.value = result.rows
  total.value = result.total
}
getRoleList()

function handleSizeChange(newSize) {
  // params.pageSize = newSize
  params.pageNum = 1
  getRoleList()
}
function handleCurrentChange(newPage) {
  // params.pageNum = newPage
  getRoleList()
}

async function showPermissionDialog(row) {
  try {
    permissionParams.roleId = row.roleId
    availablePermissionParams.roleId = row.roleId // 添加这行
    await getPermissionList()
    permissionDialogVisible.value = true

  } catch (error) {
    ElMessage.error('获取权限列表失败')
  }
}

async function getPermissionList() {
  try {
    const result = await getRolePermissionListService(permissionParams)
    permissionList.value = result.rows
    permissionTotal.value = result.total
  } catch (error) {
    console.error('getPermissionList error:', error)
    throw error
  }
}

function handlePermissionSizeChange(newSize) {
  // permissionParams.pageSize = newSize
  params.pageNum = 1
  getPermissionList()
}

function handlePermissionPageChange(newPage) {
  permissionParams.pageNum = newPage
  getPermissionList()
}

function showAddDialog() {
  addDialogVisible.value = true
}

async function handleAdd() {
  try {
    await addRoleService(addForm)
    ElMessage.success('新增成功')
    addDialogVisible.value = false
    getRoleList()
  } catch (error) {
    ElMessage.error('新增失败')
  }
}

async function handleDelete(row) {
  try {
    await ElMessageBox.confirm(
      '确定删除该角色吗?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    await deleteRoleService(row.roleId)
    ElMessage.success('删除成功')
    getRoleList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

async function handleRemovePermission(row) {
  try {
    await ElMessageBox.confirm(
      '确定移除该权限吗?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 1. 明确等待删除操作完成
    const result = await removeRolePermissionService({
      roleId: permissionParams.roleId,
      permissionId: row.permissionId
    })

    // 2. 根据实际API响应判断成功与否
    ElMessage.success('移除成功')

    // 3. 并行更新所有相关数据
    await Promise.all([
      getPermissionList(),
      getAvailablePermissionList(),
      getRoleList() // 如果需要更新角色列表
    ])
  } catch (error) {
    // 5. 更精确的错误处理
    if (error === 'cancel') {
      // 用户取消操作，不显示错误
      return
    }

    // 6. 显示更详细的错误信息
    console.error('移除权限失败:', error)
    ElMessage.error(error.response?.data?.message || error.message || '移除失败')
  }
}

async function handleAddPermission(row) {
  try {
    await ElMessageBox.confirm(
      '确定添加该权限吗?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    await addRolePermissionService({
      roleId: permissionParams.roleId,
      permissionId: row.permissionId
    })
    ElMessage.success('添加成功')
    getPermissionList()
    getAvailablePermissionList()
    getRoleList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('handleAddPermission error:', error)
      ElMessage.error(error.message || '添加失败')
    }
  }
}

async function getAvailablePermissionList() {
  try {
    const result = await getAvailablePermissionListService({
      roleId: availablePermissionParams.roleId,
      pageNum: availablePermissionParams.pageNum,
      pageSize: availablePermissionParams.pageSize,
      permissionName: availablePermissionParams.permissionName
    })
    availablePermissionList.value = result.rows
    availablePermissionTotal.value = result.total
  } catch (error) {
    console.error('getAvailablePermissionList error:', error)
    ElMessage.error('获取可关联权限失败')
  }
}

function handleTabClick(tab) {
  activeTab.value = tab.props.label;
  if (tab.props.label === '可关联权限') {
    availablePermissionParams.roleId = permissionParams.roleId;
    getAvailablePermissionList();
  } else if (tab.props.label === '已关联权限') {
    getPermissionList();
  }
}

function handleAvailablePermissionSizeChange(newSize) {
  // availablePermissionParams.pageSize = newSize
  availablePermissionParams.pageNum = 1
  getAvailablePermissionList()
}

function handleAvailablePermissionPageChange(newPage) {
  availablePermissionParams.pageNum = newPage
  getAvailablePermissionList()
}

async function onSearch() {
  params.pageNum = 1
  getRoleList()
}

async function onReset() {
  params.pageNum = 1
  params.pageSize = 10
  params.roleName = ''
  getRoleList()
}



async function onAvailablePermissionReset() {
  availablePermissionParams.pageNum = 1
  availablePermissionParams.permissionName = ''
  await getAvailablePermissionList()
}

// 修改后的搜索和重置函数
import { debounce } from 'lodash-es';

const debouncedPermissionSearch = debounce(async () => {
  if (activeTab.value === '已关联权限') {
    permissionParams.pageNum = 1;
    await getPermissionList();
  } else {
    availablePermissionParams.pageNum = 1;
    await getAvailablePermissionList();
  }
}, 500);

async function onPermissionSearch() {
  if (activeTab.value === '已关联权限') {
    permissionParams.pageNum = 1;
    await getPermissionList();
  } else {
    availablePermissionParams.pageNum = 1;
    availablePermissionParams.permissionName = permissionInputValue.value;
    await getAvailablePermissionList();
  }
}

async function onPermissionReset() {
  debouncedPermissionSearch.cancel();
  if (activeTab.value === '已关联权限') {
    permissionParams.pageNum = 1;
    permissionParams.permissionName = '';
    await getPermissionList();
  } else {
    availablePermissionParams.pageNum = 1;
    availablePermissionParams.permissionName = '';
    await getAvailablePermissionList();
  }
}



</script>

<style scoped>
.role-form {
  margin-bottom: 20px;
}

.role-table {
  width: 100%;
  height: calc(100vh - 220px);
  min-height: 400px;
  display: flex;
  flex-direction: column;
}

.el-table {
  flex: 1;
  overflow: auto;
}

.permission-text {
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
  max-width: 100%;
}

@media (max-width: 768px) {
  .role-table {
    height: auto;
  }
}
</style>
